import axios, { type InternalAxiosRequestConfig, type AxiosResponse } from 'axios'

const service = axios.create({
  baseURL: '/',
  timeout: 5000,
})
// 1. 在请求头中设置语言和token
// 2. 在响应中处理响应内容
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = localStorage.getItem('token')
    const lang = localStorage.getItem('lang')
    if (lang) {
      config.headers['Accept-Language'] = lang
    }
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data
  },
  (error) => {
    return Promise.reject(error)
  },
)

export default service
